package org.cqipc.edu.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.cqipc.edu.dao.PermissionDao;
import org.cqipc.edu.dao.RoleDao;
import org.cqipc.edu.dao.UserRoleDao;
import org.cqipc.edu.entity.Permission;
import org.cqipc.edu.entity.Role;
import org.cqipc.edu.entity.User;
import org.cqipc.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 角色Realm权限规则
 * @ClassName: RoleRealm
 * @Author: Heyue
 * @DateTime: 2020-06-22
 **/
public class RoleRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private UserRoleDao userRoleDao;


    /**
     * @Description: 授权
     * @Author: Heyue
     * @Date: 2020/6/22
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进入授权...");
        List<Integer> roleIds = new ArrayList<>();//假设用户不止一个角色ID，用于存放
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User userinfo = (User) SecurityUtils.getSubject().getPrincipal();

        /*添加权限和角色信息*/
        //拿到该用户的角色信息并交由Shiro管理
        for (Role role : roleDao.getRoleByRoleId(userRoleDao.getUserRoleByUserId(userinfo.getUserId()).getRoleId())) {
            info.addRole(role.getRoleName());
            roleIds.add(role.getRoleId());
        }
        //循环该用户的所有角色ID拿到权限信息并交由Shiro管理
        for (Integer roleId : roleIds) {
            //该用户可能会有多个权限信息，所以需要拿到每一个权限(如果该角色没有权限则不需要添加)
            if (permissionDao.getPermissionByRoleId(roleId) != null) {
                for (Permission permission : permissionDao.getPermissionByRoleId(roleId)) {
                    info.addStringPermission(permission.getPerm());
                }
            }
        }
        return info;
    }


    /**
     * @Description: 认证
     * @Author: Heyue
     * @Date: 2020/6/22
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证...");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User CurrentUser = userService.getUserByUserName(token.getUsername());
        SecurityUtils.getSubject().getSession().setAttribute("UserInfo", CurrentUser);
        if (CurrentUser != null) {
            return new SimpleAuthenticationInfo(CurrentUser, CurrentUser.getPassword(), getName());
        }
        return null;
    }
}
